package com.p2p.user.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.p2p.common.constants.Message;
import com.p2p.common.enums.ResponseEnum;
import com.p2p.common.enums.StatusEnum;
import com.p2p.common.redis.RedisService;
import com.p2p.common.redis.vo.RedisVo;
import com.p2p.common.token.TokenService;
import com.p2p.common.utils.*;
import com.p2p.user.po.User;
import com.p2p.user.po.UserLoginLog;
import com.p2p.user.po.UserRole;
import com.p2p.user.service.*;
import com.p2p.user.vo.RegisterVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class PublicServiceImpl implements PublicService {
    private static final Logger logger = LoggerFactory.getLogger(PublicServiceImpl.class);

    private static final String User = null;

    @Resource(name = "redisService")
    private RedisService<RedisVo> redisService;

    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private UserRoleService userRoleService;

    @Resource
    private TokenService tokenService;

    @Autowired
    private UserLoginLogService userLoginLogService;


    @Override
    public Message register(RegisterVo registerVo) {
        User user = registerVo.getUser();
        try {

            if (StringUtils.isEmpty(user.getContactName()) || StringUtils.getStrLength(user.getContactName()) > 10) {
                return new Message(ResponseEnum.NETBAR_CONTACT_NAME_ERROR.getCode(),
                        ResponseEnum.NETBAR_CONTACT_NAME_ERROR.getMsg());
            }
            if (!StringUtils.validatePhone(user.getMobile())) {
                return new Message(ResponseEnum.USER_PHONE_ERROR.getCode(), ResponseEnum.USER_PHONE_ERROR.getMsg());
            }

            if (!StringUtils.validateUserName(user.getUsername())) {
                return new Message(ResponseEnum.USER_NAME_ERROR.getCode(), ResponseEnum.USER_NAME_ERROR.getMsg());
            }
            if (!StringUtils.validatePassword(user.getPassword())) {
                return new Message(ResponseEnum.USER_PASSWORD_ERROR.getCode(),
                        ResponseEnum.USER_PASSWORD_ERROR.getMsg());
            }

            User dbUser = userService.selectOne(new EntityWrapper<User>().eq("username", user.getUsername()));
            if (dbUser != null) {
                return new Message(ResponseEnum.USERNAME_IS_EXIST.getCode(), ResponseEnum.USERNAME_IS_EXIST.getMsg());
            }
            Timestamp timestamp = new Timestamp(System.currentTimeMillis());

            // 创建用户表
            user.setPassword(MD5Encryption.encrypt(user.getPassword(), user.getUsername()));
            user.setCreateTime(timestamp);
            // 暂时取消审核，直接启用
            user.setStatus(StatusEnum.ENABLE.getCode());
            userService.insert(user);

            // 创建角色表，默认系统管理员
            // Role role = new Role();
            // role.setName(RoleTypeEnum.ADMINISTRATOR.getName());
            // role.setRoleType(RoleTypeEnum.ADMINISTRATOR.getCode());
            // role.setUserId(user.getId());
            // role.setCreateTime(timestamp);
            // role.setStatus(StatusEnum.ENABLE.getCode());
            // roleService.insert(role);

            // 创建用户角色关联表
            UserRole userRole = new UserRole();
            userRole.setRoleId(2l);
            userRole.setUserId(user.getId());
            userRole.setCreateTime(timestamp);
            userRole.setStatus(StatusEnum.ENABLE.getCode());
            userRoleService.insert(userRole);

            // 创建角色权限关联表，默认管理员全部权限
            // List<Long> ids = permissionService.selectAllIds();
            // for (Long id : ids) {
            // RolePermission rolePermission = new RolePermission();
            // rolePermission.setRoleId(1l);
            // rolePermission.setPermissionId(id);
            // rolePermission.setCreateTime(timestamp);
            // rolePermission.setStatus(StatusEnum.ENABLE.getCode());
            // rolePermissionService.insertOrUpdate(rolePermission);
            // }

            return new Message(ResponseEnum.SUCCESS.getCode(), ResponseEnum.SUCCESS.getMsg());
        } catch (Exception e) {
            logger.error(e.getMessage());
            return new Message(ResponseEnum.SERVER_ERROR.getCode(), ResponseEnum.SERVER_ERROR.getMsg());
        }
    }

    @Override
    public Message login(HttpServletRequest request) {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        logger.info("username=" + username + "-----------password=" + password);
        try {
            if (!StringUtils.validateUserName(username)) {
                return new Message(ResponseEnum.USER_NAME_ERROR.getCode(), ResponseEnum.USER_NAME_ERROR.getMsg());
            }
            if (!StringUtils.validatePassword(password)) {
                return new Message(ResponseEnum.USER_PASSWORD_ERROR.getCode(),
                        ResponseEnum.USER_PASSWORD_ERROR.getMsg());
            }
            User user = userService.selectOne(new EntityWrapper<User>().eq("username", username));
            if (user == null) {
                return new Message(ResponseEnum.ACCOUNT_IS_INVALID.getCode(), ResponseEnum.ACCOUNT_IS_INVALID.getMsg());
            }
            if (user.getStatus() == StatusEnum.DELETED.getCode() || user.getStatus() == StatusEnum.DISABLE.getCode()) {
                return new Message(ResponseEnum.ACCOUNT_IS_DISABLE.getCode(), ResponseEnum.ACCOUNT_IS_DISABLE.getMsg());
            }
            if (!(MD5Encryption.encrypt(password, user.getUsername()).equals(user.getPassword()))) {
                return new Message(ResponseEnum.USER_PASSWORD_ERROR.getCode(),
                        ResponseEnum.USER_PASSWORD_ERROR.getMsg());
            }
            String token = tokenService.createToken(user.getId(),null);

            // result.put("netbar_id", user.getNetbarId());
            // result.put("agent_id", 11);
            user.setLastLoginIp(IpUtils.getIp(request));
            user.setLastLoginTime(new Timestamp(System.currentTimeMillis()));
            userService.updateById(user);
            Long userId = user.getId();
            EntityWrapper<UserRole> entityWrapper = new EntityWrapper<>();
            entityWrapper.eq("user_id", userId);
            UserRole selectOne = userRoleService.selectOne(entityWrapper);
            Long roleId = selectOne.getRoleId();

            Map<String, String> result = new HashMap<String, String>();
            result.put("token", token);
            result.put("roleId", roleId.toString());
            result.put("name", user.getContactName());

            Timestamp timestamp = new Timestamp(System.currentTimeMillis());

            UserLoginLog userLoginLog = new UserLoginLog();
            userLoginLog.setLoginIp(IpUtils.getIp(request));
            userLoginLog.setCreateTime(timestamp);
            userLoginLog.setStatus(1);
            userLoginLog.setLastUpdateTime(timestamp);
            userLoginLog.setUserId(userId);
            userLoginLogService.insert(userLoginLog);
            return new Message(ResponseEnum.SUCCESS.getCode(), ResponseEnum.SUCCESS.getMsg(), result);
        } catch (Exception e) {
            logger.error(e.toString());
            return new Message(ResponseEnum.SERVER_ERROR.getCode(), ResponseEnum.SERVER_ERROR.getMsg());
        }
    }

    @Override
    public Message sendEmail(HttpServletRequest request) {
        String userName = ParamUtils.getParameter(request, "userName");
        String uemail = ParamUtils.getParameter(request, "email");
        String password = ParamUtils.getParameter(request, "password");

        if (password.length() < 6) {
            return new Message(2100, "新密码长度有误", null);
        }
        EntityWrapper<User> userEntity = new EntityWrapper<User>();
        userEntity.eq("username", userName).eq("e_mail", uemail);
        User selectOne = userService.selectOne(userEntity);
        if (selectOne == null) {
            return new Message(2100, "用户名和邮箱不存在", null);
        } else {


            try {

                String secretKey = UUID.randomUUID().toString(); // 密钥

                // 更新uuid到redis

                RedisVo secret = new RedisVo("email:secretKey:" + userName, secretKey);
                secret.setTimeUnit(TimeUnit.MINUTES);
                secret.setValidTime(30l);
                redisService.update(secret);

                RedisVo pass = new RedisVo("email:pass:" + userName, password);
                pass.setTimeUnit(TimeUnit.MINUTES);
                pass.setValidTime(30l);
                redisService.update(pass);

                String key = userName + "$" + secretKey;
                String digitalSignature = MD5Encryption.encrypt(key.getBytes());// 数字签名

                String remoteHost = request.getRemoteHost();

                logger.info("用户真实ip====" + remoteHost);
                logger.info("域名====" + request.getServerName());

                String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + "/";
                String resetPassHref = basePath + "user/sucessfindp.html?sid=" + digitalSignature + "&userName="
                        + userName;
                String findpw = basePath + "user/findp.html";
                String emailContent = "请勿回复本邮件.点击下面的链接,激活密码<br/><a href=" + resetPassHref + " target='_BLANK'>"
                        + resetPassHref + "</a>  或者    <a href=" + resetPassHref + " target='_BLANK'>点击我激活密码</a>"
                        + "<br/>tips:本邮件超过30分钟,链接将会失效，需要重新申请'重置密码'" + "<br/><a  href=" + findpw
                        + " target='_BLANK'>点击我进入重新申请密码页面</a>";

                MailUtil.sendEmaillHTML(new String[]{uemail}, emailContent, "找回密码");

                return new Message(ResponseEnum.SUCCESS.getCode(), ResponseEnum.SUCCESS.getMsg(), null);
            } catch (Exception ex) {
                logger.error(ex.getMessage(), ex);
                return new Message(8100, "邮件发送失败", null);
            }

        }

    }

    @Override
    public Message checkEmail(HttpServletRequest request) {
        String sid = ParamUtils.getParameter(request, "sid");
        String userName = ParamUtils.getParameter(request, "userName");

        if (sid.equals("") || userName.equals("")) {
            return new Message(8100, "链接不完整,请重新生成", null);
        }

        EntityWrapper<User> userEntity = new EntityWrapper<User>();
        userEntity.eq("username", userName);
        User selectOne = userService.selectOne(userEntity);

        if (selectOne != null) {

            RedisVo redisVo = redisService.get("email:secretKey:" + userName);
            RedisVo passVo = redisService.get("email:pass:" + userName);

            if (redisVo == null || passVo == null) { // 表示已经过期
                return new Message(8100, "链接已经过期,请重新申请找回密码.");

            }

            String value = redisVo.getValue();
            String password = passVo.getValue();

            String key = userName + "$" + value;// 数字签名

            String digitalSignature = MD5Encryption.encrypt(key.getBytes());// 数字签名

            System.out.println("digitalSignature>>>>" + digitalSignature);

            if (!digitalSignature.equals(sid)) {
                return new Message(8100, "链接不正确,是否已经过期了?重新申请吧.");

            } else {

                selectOne.setPassword(MD5Encryption.encrypt(password, selectOne.getUsername()));
                boolean updateFlag = userService.updateById(selectOne);
                if (updateFlag) {
                    return new Message(ResponseEnum.SUCCESS.getCode(), ResponseEnum.SUCCESS.getMsg(), null);
                } else {
                    return new Message(ResponseEnum.SERVER_ERROR.getCode(), ResponseEnum.SERVER_ERROR.getMsg());
                }

            }
        } else {
            return new Message(8100, "链接错误,无法找到匹配用户,请重新申请找回密码.");

        }
    }

	
}

